from rest_framework import serializers

from goods.models import GoodsChannel, GoodsChannelGroup, GoodsCategory


# 频道
class ChannelSerializer(serializers.ModelSerializer):
    category = serializers.CharField(read_only=True)
    category_id = serializers.IntegerField()
    group = serializers.CharField(read_only=True)
    group_id = serializers.IntegerField()

    class Meta:
        model = GoodsChannel
        fields = "__all__"

    def create(self, validated_data):
        try:
            cat = GoodsCategory.objects.get(id=validated_data["category_id"])
            channel = GoodsChannel.objects.create(**validated_data)
            GoodsCategory.objects.create(name=cat.name)
        except:
            raise serializers.ValidationError("新增频道失败")
        else:
            return channel


# 频道组
class ChannelGroupSerializer(serializers.ModelSerializer):
    class Meta:
        model = GoodsChannelGroup
        fields = ['id', 'name']


# 一级分类
class CategoriesSerializer(serializers.ModelSerializer):
    class Meta:
        model = GoodsCategory
        # fields = ['id', 'name']
        fields = '__all__'
